<template>
    <div class="min-h-screen flex flex-col">

        <!-- 登录注册 -->
        <header class="header bg-white p-4 shadow-md flex justify-between items-center">

            <div class="container flex items-center">
                <div class="links-container"> <!-- 新增的容器 -->
                    <a href="#" class="flex items-center text-gray-600 hover:text-blue-500">
                        <i class="icon-download"></i>
                        <span class="ml-1">下载App</span>
                    </a>
                    <a href="#" class="text-blue-500 font-bold hover:underline">栏目收费说明</a>
                </div>
                <!-- 使用 v-if/v-else 来条件渲染登录/注册按钮或用户信息 -->
                <div v-if="!username" class="lrcs items-center space-x-4"> <!-- Flex 布局让内容一行排列 -->
                    <RouterLink class="btn-login" :to="{ name: 'Login', query: { redirecturl: router.currentRoute.value.fullPath } }">登录</RouterLink>
                    <RouterLink class="btn-register" to='/register'>注册</RouterLink>
                </div>
                <div v-else class="user-info flex items-center space-x-3"> <!-- 用户信息 -->
                    <img :src="avatar" alt="用户头像" class="user-avatar w-8 h-8 rounded-full" />
                    <span>{{ username }}</span>
                    <span class="text-logout" @click="logout">退出</span>
                </div>

            </div>
        </header>

        <!-- 搜索 -->
        <div class="search-header">
            <div class="search-wrapper">
                <h1 class="text-a">丁香医生</h1>
                <input type="text" v-model="searchQuery" placeholder="搜索疾病、医院、药品" class="search-input" />
                <button class="search-button">搜索</button>
            </div>
        </div>

        <!-- 顶部导航 -->
        <nav class="main-nav">
            <router-link v-for="item in navigationItems" :key="item.name" :to="item.link" class="nav-link">
                {{ item.name }}
            </router-link>
        </nav>

        <!-- 面包屑 -->
        <div class="breadcrumb-container mb-4">
            <nav class="flex items-center text-sm">
                <router-link to="/" class="text-emerald-500 hover:text-emerald-600">首页</router-link>
                <span class="mx-2 text-gray-400">›</span>
                <router-link to="/hospital" class="text-emerald-500 hover:text-emerald-600">查医院</router-link>


            </nav>

            <!-- 分类 -->
            <div class="qa-container">
                <div class="content-wrapper">
                    <div class="categories-container">
                        <div class="category-box">
                            <div class="category-header">科室</div>
                            <div class="category-content">
                                <button v-for="dept in departments" :key="dept.id" @click="selectDepartment(dept)"
                                    :class="['category-btn', selectedDepartment?.id === dept.id ? 'active' : '']">
                                    {{ dept.name }}
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- 医院列表 -->
                    <div class="main-content-area">
                        <div class="hospital-section">
                            <!-- 医院列表 -->
                            
                            <div class="hospital-list-box">
                                <div class="hospital-card" v-for="(item, index) in paginatedHospitals" :key="item.id"
                                    @click="navigateToHospital(item.id)">
                                    <!-- 左侧图片 -->
                                    <img :src="item.covers || '/default-hospital.png'" alt="Hospital"
                                        class="hospital-cover" />

                                    <!-- 右侧信息 -->
                                    <div class="hospital-info">
                                        <!-- 名称和等级 -->
                                        <h4 class="hospital-title">
                                            {{ item.name }}
                                            <span class="hospital-item-level">{{ item.get_level_display }}</span>
                                        </h4>
                                        <!-- 地址 -->
                                        <p class="hospital-item-address">{{ item.address }}</p>
                                    </div>
                                </div>

                                <!-- 分页 -->
                                <div class="pagination">
                                    <button v-for="page in Math.ceil(hospitals.length / itemsPerPage)" :key="page"
                                        :class="['pagination-btn', { active: page === currentPage }]"
                                        @click="changePage(page)">
                                        {{ page }}
                                    </button>
                                </div>
                            </div>



                            <!-- 医生侧边界面 -->
                            <div class="sidebar-box department-doctors">
                                <h3>相关科室医生</h3>
                                <div class="doctor-card" @click="navigateToDoctor(doctor.id)"
                                    v-for="doctor in departmentDoctors" :key="doctor.id">
                                    <img :src="doctor.avatar" alt="Doctor" class="doctor-avatar" />
                                    <div class="doctor-info">
                                        <div class="doctor-name">{{ doctor.name }}</div>
                                        <div class="doctor-title-dept">
                                            {{ doctor.get_title_display }} {{ doctor.department }}
                                        </div>
                                        <div class="doctor-hospital">{{ doctor.hospital }}</div>
                                        <div class="doctor-stats">
                                            <span class="doctor-price">¥{{ doctor.consultation_price }}</span>
                                            <span class="doctor-rating">{{ doctor.rating }}分</span>
                                            <span class="doctor-consults">{{ doctor.consultation_count }}问答</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>


                </div>
            </div>


            <!-- 底部导航 -->
            <footer class="mt-auto">
                <div class="bottom-links">
                    <a target="_blank" href="http://www.dxy.cn/pages/copyright.html" rel="nofollow">版权声明</a>
                    <a target="_blank" href="https://dxy.com/column/board" rel="nofollow">作者编委</a>
                    <a target="_blank" href="https://ask.dxy.com/ama/index" rel="nofollow">丁香医生</a>
                    <a href="mailto:doctor@dxy.com" rel="nofollow">投稿邮箱 doctor@dxy.com</a>
                    <a target="_blank">客服电话：0571-22931767</a>
                </div>
            </footer>

        </div>
    </div>

</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import { jwtDecode } from 'jwt-decode';
import { RouterLink } from 'vue-router';


const router = useRouter();
const username = ref<string | null>(null);
const avatar = ref<string | null>(null);
const searchQuery = ref('');
const navigationItems = [
    { name: '问医生', link: '/sections' },
    { name: '查疾病', link: '/disease' },
    { name: '查药品', link: '/medicine' },
    { name: '查医院', link: '/hospital' },
    { name: '查检查/手术', link: '/examination' },
    { name: '查疫苗', link: '/vaccine' },
    { name: '急救指南', link: '/emergency' },
    { name: '测一测', link: '/test' },
    { name: '科普视频', link: '/videos' }
];

interface Department {
    id: number;
    name: string;
}

interface Doctor {
    id: number;
    name: string;
    avatar: string;
    get_title_display: string;
    hospital: string;
    department: string;
    price: number;
    rating: number;
    consult_count: number;
}

const departments = ref<Department[]>([]);
const departmentDoctors = ref<Doctor[]>([]);
const hospitals = ref<any[]>([]);
const selectedDepartment = ref<Department | null>(null);

// 登录
// const fetchUserInfo = async () => {
//     const token = localStorage.getItem('token');
//     if (token) {
//         const payload = JSON.parse(atob(token.split('.')[1]));
//         const userId = payload.id;



//         const response = await fetch(`http://127.0.0.1:8000/user/userinfo/${userId}/`, {
//             headers: { 'Authorization': `Bearer ${token}` }
//         });
//         const data = await response.json();
//         username.value = data.username;
//         avatar.value = data.avatar;
//     }
// };
const fetchUserInfo = async () => { 
    const token = localStorage.getItem('token');
    if (token) {
        const payload = ref<any>(jwtDecode(token));
        username.value = payload.value.username;
        avatar.value = 'http://127.0.0.1:8000/uploads/' + payload.value.avatar;
        console.log(avatar.value);
    }

}

const logout = () => {
    localStorage.removeItem('token');
    username.value = null;
    avatar.value = null;
};



// 获取科室
const fetchDepartments = async () => {
    try {
        const response = await axios.get('http://127.0.0.1:8000/doctor/department/0/');
        departments.value = response.data;
        if (departments.value.length > 0) {
            selectDepartment(departments.value[0]);
        }
    } catch (error) {
        console.error('Error fetching departments:', error);
    }
};

const fetchHospitals = async (departmentId:number) => {
    try {
        const response = await axios.get(`http://127.0.0.1:8000/doctor/hospital/${departmentId}/`);
        console.log(response.data);
        hospitals.value = response.data;

 }    catch (error) {
        console.error('Error fetching hospitals:', error);
    }
  };

const selectDepartment = async (department: Department) => {
    selectedDepartment.value = department;
    
    await Promise.all([
        fetchHospitals(department.id),
        
        

        fetchDepartmentDoctors(department.id)
    ]);
};

// 获取医生
const fetchDepartmentDoctors = async (departmentId: number) => {
    try {
        const response = await axios.get(`http://127.0.0.1:8000/doctor/doctor/${departmentId}/`);
        departmentDoctors.value = response.data.slice(0, 3);
    } catch (error) {
        console.error('Error fetching department doctors:', error);
    }
};

// 分页
const currentPage = ref(1); // 当前页码
const itemsPerPage = 5; // 每页展示的医院数量

// 计算当前页要显示的医院数据
const paginatedHospitals = computed(() => {
    const start = (currentPage.value - 1) * itemsPerPage;
    const end = start + itemsPerPage;
    return hospitals.value.slice(start, end);
});

// 切换页面
const changePage = (page: number) => {
    currentPage.value = page;
};




// 点击

const navigateToHospital = (hospitalId: number) => {
    // router.push(`/hospital/${hospitalId}`);
    window.open(`/hospital/${hospitalId}`, '_blank');
 }

const navigateToDoctor = (doctorId: number) => {
    // router.push(`/doctor/${doctorId}`);
    window.open(`/doctor/${doctorId}`, '_blank');
};


onMounted(() => {
    fetchDepartments();
    fetchUserInfo();
    fetchHospitals(1);
    
});
</script>

<style scoped>
/* 登录注册 */
/* Header Styling */
.header {
    background-color: #ffffff;
    /* White background */
    color: #333333;
    /* Gray text color */
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    /* Subtle shadow */
    padding: 16px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

/* Left Content Links */
.header a {
    text-decoration: none;
    color: #666666;
    font-size: 14px;
    display: flex;
    align-items: center;
    transition: color 0.3s ease;
}

.header a:hover {
    color: #00b38a;
    /* Match green color on hover */
}

.header a.text-blue-500 {
    color: #00b38a;
    /* Green color for special links */
    font-weight: bold;
    margin-left: 16px;
}

.text-logout{
    margin-left: 16px;
    background-color: transparent;
    /* 透明背景 */
    border: none;
    /* 无边框 */
    color: #666666;
    /* 文本颜色与下载链接一致 */
    padding: 0;
    /* 移除内边距 */
    font-size: 14px;
    font-weight: normal;
    /* 正常字体粗细 */
    cursor: pointer;
    text-decoration: none;
    /* 移除下划线 */
    transition: color 0.3s ease;
    /* 颜色过渡效果 */
}

.text-logout:hover {
    color: #00b38a;
    text-decoration: underline;

}


.container {
    display: flex;
    align-items: center;
    
    flex-wrap: nowrap;
   
    gap: 16px;
    margin-right: 350px;
    
}

/* 可以添加一个包含栏目、下载等链接的容器样式 */
.links-container {
    display: flex;
    align-items: center;
    /* 之间的间隔 */
    
    
    
};

/* Right Content Buttons */

.btn-login{
    background-color: transparent;
        /* 透明背景 */
        border: none;
        /* 无边框 */
        color: #666666;
        /* 文本颜色与下载链接一致 */
        padding: 0;
        /* 移除内边距 */
        font-size: 14px;
        font-weight: normal;
        /* 正常字体粗细 */
        cursor: pointer;
        text-decoration: none;
        /* 移除下划线 */
        transition: color 0.3s ease;
        /* 颜色过渡效果 */
}
.btn-register {
    background-color: transparent;
    /* 透明背景 */
    border: none;
    /* 无边框 */
    color: #666666;
    /* 文本颜色与下载链接一致 */
    padding: 0;
    /* 移除内边距 */
    font-size: 14px;
    font-weight: normal;
    /* 正常字体粗细 */
    cursor: pointer;
    text-decoration: none;
    /* 移除下划线 */
    transition: color 0.3s ease;
    /* 颜色过渡效果 */
    margin-left: 13px;
}

.lrcs{
    display: flex;
    align-items: center;
    
}
/* 添加伪类来模仿下载链接的hover效果 */
.btn-login:hover,
.btn-register:hover {
    color: #00b38a;
    /* 悬停时变为绿色 */
    text-decoration: underline;
    /* 悬停时添加下划线 */
}

/* User Info Styling */
.user-info {
    display: flex;
    align-items: center;
}

.user-info .user-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    /* Circular avatar */
    object-fit: cover;
    
}

.user-info span {
    font-size: 14px;
    font-weight: 500;
    color: #333333;
}
/* 搜索 */
.search-header {
    background-color: #fff;
    padding: 20px 0;
}

.search-wrapper {
    max-width: 600px;
    margin: 0 auto;
    display: flex;
    gap: 10px;
}

.text-a {
    font-size: 32px;
    font-weight: 700;
    color: #00b38a;
    margin: 0 auto;
    letter-spacing: 1px;
}

.search-input {
    flex: 1;
    padding: 12px 20px;
    border: 2px solid #00b38a;
    border-radius: 24px;
    font-size: 16px;
    outline: none;
}

.search-button {
    padding: 12px 30px;
    background-color: #00b38a;
    color: white;
    border: none;
    border-radius: 24px;
    cursor: pointer;
    font-size: 16px;
}

/* 顶部导航 */
.main-nav {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 10px 0;
    background-color: #fff;
    border-bottom: 1px solid #eee;
}

.nav-link {
    padding: 6px 16px;
    color: #666;
    text-decoration: none;
    font-size: 14px;
    transition: color 0.2s;
}

.nav-link:hover {
    color: #00b38a;
}

/* 面包屑导航 */
.breadcrumb-container {
    max-width: 1000px;
    margin: 0 auto;
}

.breadcrumb-container nav .text-emerald-500 {
    transition: color 0.3s ease;
}

.breadcrumb-container nav .text-emerald-500:hover {
    color: #00b38a;
}

/* 底部 */
.bottom-links {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 8px;
    padding: 24px;
    background-color: #f5f5f5;
}

.bottom-links a {
    color: #666;
    text-decoration: none;
    padding: 4px 8px;
}

.bottom-links a:hover {
    color: #00b38a;
}

/* 分类 */
.qa-container {
    background-color: #f8f9fa;
    min-height: 100vh;
    padding: 24px 0;
}

.content-wrapper {
    max-width: 1000px;
    margin: 0 auto;
    padding: 0 20px;
}

.categories-container {
    margin-bottom: 32px;
}

.category-box {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    margin-bottom: 16px;
    padding: 20px;
}

.category-header {
    color: #333;
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #eee;
}

.category-content {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
}

.category-btn {
    padding: 6px 16px;
    background-color: #f5f5f5;
    border: none;
    border-radius: 4px;
    color: #666;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.2s ease;
    white-space: nowrap;
}

.category-btn:hover {
    background-color: #e6f7f4;
    color: #00b38a;
}

.category-btn.active {
    background-color: #00b38a;
    color: white;
}


.sidebar-box {
    flex: 1;
    /* 占模块的 1/3 宽度 */
    background: white;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    overflow-y: auto;
}

/* 医生列表容器 */

.sidebar-box.department-doctors {
    flex-shrink: 0;
    /* 防止医生模块被压缩 */
    flex-basis: 350px;
    /* 固定医生模块的宽度 */
    max-height: 100%;
    /* 保证医生模块完全展示 */
    overflow-y: auto;
    /* 允许医生模块滚动 */
   
}
/* 医生标题 */
.sidebar-box h3 {
    font-size: 18px;
    font-weight: 500;
    color: #333;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #eee;
}

/* 医生卡片 */
.doctor-card {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    cursor: pointer;
    padding: 12px;
    border-radius: 8px;
    transition: background-color 0.2s;
}

.doctor-card:hover {
    background-color: #f5f5f5;
}

.doctor-avatar {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    object-fit: cover;
}

.doctor-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.doctor-name {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    line-height: 1.2;
}

.doctor-title-dept {
    font-size: 14px;
    color: #666;
    line-height: 1.2;
}

.doctor-hospital {
    font-size: 14px;
    color: #666;
    line-height: 1.2;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.doctor-stats {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-top: 2px;
}

.doctor-price {
    color: #00b38a;
    font-size: 14px;
    font-weight: 500;
}

.doctor-rating,
.doctor-consults {
    color: #666;
    font-size: 14px;
}

/* 医院列表 */
/* 主模块容器 */
.main-content-area {
    display: flex;
    gap: 16px;
    margin-top: 24px;
    overflow: hidden;
    /* 隐藏超出模块的内容 */
    align-items: flex-start;
    /* 确保两个部分顶部对齐 */
}

/* 医院列表 */
.hospital-section {
    display: flex;
    width: 100%;
    /* 整个模块的宽度 */
    gap: 16px;
    /* 医院列表和医生列表之间的间隔 */
}

/* 医院列表容器样式 */
.hospital-list-box {
    display: flex;
    flex-direction: column;
    gap: 16px;
    max-height: 600px;
    /* 限制医院列表的最大高度 */
    overflow-y: auto;
    /* 滚动显示超出内容 */
    position: relative;
}

.hospital-list-box::-webkit-scrollbar {
    display: none;
    /* 隐藏滚动条 */
}

/* 单个医院卡片样式 */
.hospital-card {
    display: flex;
    align-items: flex-start;
    background: white;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    transition: box-shadow 0.3s ease, transform 0.3s ease;
    max-width: 100%;
    /* 限制卡片的宽度 */
    overflow: hidden;
    /* 超出的内容不展示 */
    cursor: pointer;
}

.hospital-card:hover {
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
    transform: scale(1.02);
}

/* 图片样式 */
.hospital-cover {
    width: 80px;
    height: 80px;
    border-radius: 4px;
    object-fit: cover;
    margin-right: 16px;
    flex-shrink: 0;
}

/* 信息部分 */
.hospital-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    overflow: hidden;
    /* 超出信息部分的内容隐藏 */
}

/* 名称和等级 */
.hospital-title {
    font-size: 18px;
    /* 增大医院名称字体 */
    font-weight: bold;
    color: #333333;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 8px;
    white-space: nowrap;
    /* 禁止换行 */
    overflow: hidden;
    /* 超出的文本隐藏 */
    text-overflow: ellipsis;
    /* 显示省略号 */
}

/* 医院等级 */
.hospital-item-level {
    background-color: #ffcc00;
    color: white;
    padding: 2px 6px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: bold;
    white-space: nowrap;
    /* 禁止换行 */
}

/* 地址 */
.hospital-item-address {
    font-size: 14px;
    color: #666666;
    line-height: 1.4;
    margin-top: 4px;
    white-space: nowrap;
    /* 禁止换行 */
    overflow: hidden;
    /* 超出文本隐藏 */
    text-overflow: ellipsis;
    /* 显示省略号 */
}

/* 分页 */

.pagination {
    margin-top: auto;
    /* 自动占用顶部的剩余空间，确保在底部 */
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 12px 0;
    background-color: #fff;
    /* 底部的背景色与医院列表一致 */
    border-top: 1px solid #e6e6e6;
    /* 增加顶部边框以分隔医院列表 */
    gap: 12px;
}

.pagination-btn {
    width: 36px;
    height: 36px;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px solid #ddd;
    border-radius: 4px;
    background-color: #f5f5f5;
    font-size: 14px;
    color: #333;
    cursor: pointer;
    transition: all 0.2s ease;
}

.pagination-btn:hover {
    background-color: #00b38a;
    color: white;
    border-color: #00b38a;
}

.pagination-btn.active {
    background-color: #00b38a;
    color: white;
    border-color: #00b38a;
    font-weight: bold;
}
</style>